package com.lyeducation.util;

import java.security.MessageDigest;

public class MD5Util {
  private static final String[] HEXDIGITS = {
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"
  };

  /**
   * 转换字节数组为16进制字串
   *
   * @param b 字节数组
   * @return 16进制字串
   */
  public static String byteArrayToHexString(byte[] b) {
    StringBuilder resultSb = new StringBuilder();
    for (byte aB : b) {
      resultSb.append(byteToHexString(aB));
    }
    return resultSb.toString();
  }

  /**
   * 转换byte到16进制
   *
   * @param b 要转换的byte
   * @return 16进制格式
   */
  private static String byteToHexString(byte b) {
    int n = b;
    if (n < 0) {
      n = 256 + n;
    }
    int d1 = n / 16;
    int d2 = n % 16;
    return HEXDIGITS[d1] + HEXDIGITS[d2];
  }

  /**
   * MD5编码
   *
   * @param origin 原始字符串
   * @return 经过MD5加密之后的结果
   */
  public static String encodeMD5(String origin) {
    String resultString = null;
    try {
      resultString = origin;
      MessageDigest md = MessageDigest.getInstance("MD5");
      md.update(resultString.getBytes("UTF-8"));
      resultString = byteArrayToHexString(md.digest());
    } catch (Exception e) {
      e.printStackTrace();
    }
    return resultString;
  }

  public static final String customMD5(String s) {
    return customMD5("MD5", s);
  }

  public static final String customMD5(String key, String s) {
      char[] hexDigits2 = {
              '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
      };
    try {
      byte[] btInput = s.getBytes();
      // 获得MD5摘要算法的 MessageDigest 对象
      MessageDigest mdInst = MessageDigest.getInstance(key);
      // 使用指定的字节更新摘要
      mdInst.update(btInput);
      // 获得密文
      byte[] md = mdInst.digest();
      // 把密文转换成十六进制的字符串形式
      int j = md.length;
        char[] str = new char[j * 2];
      int k = 0;
      for (int i = 0; i < j; i++) {
        byte byte0 = md[i];
        str[k++] = hexDigits2[byte0 >>> 4 & 0xf];
        str[k++] = hexDigits2[byte0 & 0xf];
      }
      return new String(str);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
}
